package cn.meng.base.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.meng.base.service.RedisService;
import cn.meng.base.service.UserService;
import cn.meng.base.utils.SendMailUtil;
import cn.meng.base.vo.BusinessException;
import cn.meng.base.vo.UserVo;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * 登录、注销
 *
 * @author 万梦辉
 */
@RestController
public class LoginController {

    @Autowired
    RedisService redis;
    @Autowired
    private UserService userService;
    @Autowired
    private SendMailUtil sendMailUtil;

    @RequestMapping("/login")
    public String login(@RequestBody String parms) throws BusinessException {
        JSONObject jsonObject = JSONUtil.parseObj(parms);
        String username = (String) jsonObject.get("username");
        String password = (String) jsonObject.get("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        HashMap<Object, Object> resultMessage = new HashMap<>();
        try {
            subject.login(token);
            //设置默认登录过期时间，其他时间 单位毫秒
            subject.getSession().setTimeout(1800000);
            resultMessage.put("role", redis.getValue("role"));
            resultMessage.put("success", true);
        } catch (AuthenticationException e) {
            resultMessage.put("success", false);
            resultMessage.put("role", null);
            resultMessage.put("error", "用户名或密码错误");
        }
        return JSON.toJSONString(resultMessage);
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        HashMap<Object, Object> resultMessage = new HashMap<>();
        resultMessage.put("message", "注销成功");
        return JSON.toJSONString(resultMessage);
    }

    @RequestMapping("/forgetPassword")
    public String forgetPassword(@RequestBody String parms) throws BusinessException {
        JSONObject jsonObject = JSONUtil.parseObj(parms);
        String email = (String) jsonObject.get("email");
        UserVo user = userService.getUserByEmail(email);
        if (null == user) {
            throw new BusinessException(500, "未找到该邮箱对应的用户信息，请检查邮箱填写是否正确");
        }
        HashMap<String, Object> result = new HashMap<>();
        sendMailUtil.forgetPassword(user);
        result.put("success", true);
        result.put("tip", "邮件发送成功，请及时查收");
        return JSON.toJSONString(result);
    }

}
